<template>
  <div>
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="搜索中心"
      left-arrow
      @click-left="$router.back()"
      fixed
      placeholder
    />
    <!-- 搜索栏 -->
    <van-search
      v-model="key"
      show-action
      placeholder="请输入搜索关键词"
      @input="onInput"
      @search="onSearch"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <!-- 历史记录cell 联想区域-->
    <van-cell-group v-if="!key">
      <van-cell title="历史记录" icon="search" />
      <van-cell
        v-for="(item, index) in historyList"
        :key="index"
        :title="item"
        @click="goSearch(item)"
      />
    </van-cell-group>
    <van-cell-group v-else>
      <van-cell v-for="(item, index) in colorList" :key="index">
        <div v-html="item" @click="goSearch(suggestList[index])"></div>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { suggestAPI } from '@/api/search'
export default {
  name: 'MySearch',
  data () {
    return {
      key: '',
      suggestList: [],
      historyList: JSON.parse(localStorage.getItem('history')) || []
    }
  },
  methods: {
    goSearch (item) {
      this.key = item
      this.onSearch()
    },
    onSearch () {
      if (this.key === '') return this.$toast('请输入搜索内容')
      const idx = this.historyList.indexOf(this.key)
      if (idx !== -1) {
        this.historyList.splice(idx, 1)
      }
      this.historyList.unshift(this.key)
      localStorage.setItem('history', JSON.stringify(this.historyList))
      this.$router.push({
        name: 'SearchResults',
        query: {
          key: this.key
        }
      })
    },
    async onInput () {
      if (this.key === '') return
      const res = await suggestAPI({
        q: this.key
      })
      //   console.log(res)
      if (res.data.options[0]) {
        this.suggestList = res.data.options
      } else {
        this.suggestList = []
      }
    }
  },
  computed: {
    colorList () {
      return this.suggestList.map(v => {
        return v.replace(this.key, `<span style="color:red">${this.key}</span>`)
      })
    }
  }
}
</script>

<style scoped></style>
